import React, { Component } from "react";

export default class App extends Component {
    state = {
        firstName: '1',
        lastName: '2',
        note: '',
        hobby: '篮球',
        sex: '男',
        course: []
    }

    handler = (event) => {
        this.setState({
            [event.target.name]: event.target.value
        })
    }

    changeSex = (e) => {
        this.setState({
            [e.target.name]: e.target.value
        })
    }

  changeCourse = (e) => {
      const arr = this.state.course
      const index = arr.findIndex(item => item === e.target.value)
      if (index === -1 && e.target.checked) {
        arr.push(e.target.value)
      }
      if (index !== -1 && !e.target.checked) {
          arr.splice(index, 1)
      }

      this.setState({
          course: arr
      })
  }


    render() {
        return (
            <div>
                {/* 通过input的change事件改变 ,,事件委托*/}
                <input type="text" name="firstName" value={this.state.firstName} onChange={this.handler} /> +
                <input type="text" name="lastName" value={this.state.lastName} onChange={this.handler} /> =
                {Number(this.state.firstName) + Number(this.state.lastName)}

                <br />
                <textarea name="note" value={this.state.note} onChange={this.handler}></textarea>
                {this.state.note}

                <br />
                <select name="hobby" value={this.state.hobby} onChange={this.handler}>
                    <option value="篮球">篮球</option>
                    <option value="排球">排球</option>
                    <option value="网球">网球</option>
                    <option value="足球">足球</option>
                    <option value="羽毛球">羽毛球</option>
                </select>
                {this.state.hobby}

                <br />
                <input name="sex" type="radio" onChange={this.changeSex} value="男" />男
                <input name="sex" type="radio" onChange={this.changeSex} value="女" />女
                ---- {this.state.sex}

                <br />

                <input name="course" onChange={this.changeCourse} type="checkbox" value="vue" />vue
                <input name="course" onChange={this.changeCourse} type="checkbox" value="react" />react
                <input name="course" onChange={this.changeCourse} type="checkbox" value="小程序" />小程序
                <input name="course" onChange={this.changeCourse} type="checkbox" value="jQuery" />jQuery
                -- {
                    this.state.course.map(item => {
                        return (
                            <div key={item}>{item}</div>
                        )
                    })
                }
            </div>
        )
    }
}